package com.tangyuan.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.config.RedissonConfig;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.dto.UserActionDto;
import com.tangyuan.feignapis.user.IUserActionFeignClient;
import com.tangyuan.model.UserVideoCollection;
import com.tangyuan.model.Video;
import com.tangyuan.video.mapper.VideoCollectionMapper;
import com.tangyuan.video.mapper.VideoMapper;
import com.tangyuan.video.service.VideoCollectionService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class VideoCollectionServiceImpl extends ServiceImpl<VideoCollectionMapper, UserVideoCollection> implements VideoCollectionService {
    @Autowired
    VideoCollectionMapper videoCollectionMapper;
    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private IUserActionFeignClient userActionFeignClient;

    private final RedissonClient redissonClient = RedissonConfig.createRedissonClient();

    @Override
    public Result<Object> saveCollectionVideo(Long userId, Long videoId) {
        RLock lock = redissonClient.getLock("videoCollection" + videoId + "-" + userId);
        lock.lock();
        try {
            Video video = videoMapper.selectById(videoId);
            if (video == null) {
                return Result.build(null, ResultCodeEnum.NO_DATA);
            }
            UserActionDto dto = new UserActionDto();
            dto.setUserId(userId);
            dto.setMovieId(videoId);
            dto.setCategoryId(video.getCategoryId());
            UserVideoCollection collection = this.getOne(new LambdaQueryWrapper<UserVideoCollection>()
                    .eq(UserVideoCollection::getVideoId, videoId)
                    .eq(UserVideoCollection::getUserId, userId));
            if (collection == null) {
                //封装收藏信息
                collection = new UserVideoCollection();
                collection.setUserId(userId);
                collection.setVideoId(videoId);
                collection.setCollectionDate(new Date());

                dto.setCollection(1.0f);
                Result<String> actionResult = userActionFeignClient.getUserAction(dto);
                if (!actionResult.isOk()){
                    return Result.build(null,ResultCodeEnum.HANDLING_USER_BEHAVIOR_ERROR);
                }
                videoMapper.saveCollectionNum(videoId, 1);
                videoCollectionMapper.insert(collection);
            } else {
                if (collection.getIsDelete() == 0) {
                    dto.setCollection(-1.0f);
                    Result<String> actionResult = userActionFeignClient.getUserAction(dto);
                    if (!actionResult.isOk()){
                        return Result.build(null,ResultCodeEnum.HANDLING_USER_BEHAVIOR_ERROR);
                    }
                    baseMapper.removeCollectionVideo(userId, videoId, 1);
                    videoMapper.saveCollectionNum(videoId, -1);
                } else {
                    dto.setCollection(1.0f);
                    Result<String> actionResult = userActionFeignClient.getUserAction(dto);
                    if (!actionResult.isOk()){
                        return Result.build(null,ResultCodeEnum.HANDLING_USER_BEHAVIOR_ERROR);
                    }
                    baseMapper.removeCollectionVideo(userId, videoId, 0);
                    videoMapper.saveCollectionNum(videoId, 1);
                }
            }
        } catch (Exception e) {
            log.error("用户收藏视频异常:" + e.getMessage());
        } finally {
            lock.unlock();
        }
        return Result.ok();
    }

    /**
     * 分页获取我的收藏VideoID
     * @param userId 用户ID
     */
    @Override
    public List<Long> getVideoIdByUserId(Long userId, Integer pageNum, Integer pageSize) {
        if(userId == null || userId == 0){
            return new ArrayList<>();
        }
        QueryWrapper<UserVideoCollection> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserVideoCollection::getUserId,userId);
        wrapper.lambda().eq(UserVideoCollection::getIsDelete,0);
        wrapper.lambda().orderByDesc(UserVideoCollection::getCollectionDate);
        List<UserVideoCollection> records = baseMapper.selectPage(new Page<>(pageNum, pageSize), wrapper).getRecords();
        if(CollectionUtils.isEmpty(records)){
            return new ArrayList<>();
        }
        return records.stream().map(UserVideoCollection::getVideoId).collect(Collectors.toList());
    }

}
